<template>
  <div class="mod-config">
    <el-form
      :inline="true"
      @keyup.enter.native="getDataList()">
      <el-form-item label="标题">
        <el-input v-model="searchName" clearable></el-input>
      </el-form-item>
       <el-form-item label="类型" prop="type">
         <el-select v-model="searchType" placeholder="请选择" style="width:100%" clearable="">
            <el-option
              v-for="(item,index) in types" 
              :key="index"
              :label="item"
              :value="index+1">
            </el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>        
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%">
      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        label="标题">
      </el-table-column>
      <!-- <el-table-column
        prop="content"
        header-align="center"
        align="center"
        label="内容">
      </el-table-column> -->
      <el-table-column
        prop="imgUrl"
        header-align="center"
        align="center"
        width="120px"
        label="图片">
        <template slot-scope="scope" v-if="scope.row.imgUrl">
          <viewer>
            <img :src="baseImageUrl + scope.row.imgUrl" width="100%" />
          </viewer>
        </template>
      </el-table-column>
      <el-table-column
        prop="type"
        header-align="center"
        align="center"
        label="类型">
         <template slot-scope="scope">
           <el-tag>{{btnMap(scope.row.type)}}</el-tag>
        </template>
      </el-table-column> 
      <el-table-column
        prop="isHome"
        header-align="center"
        align="center"
        label="是否首页展示">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isHome === 1" size="small">是</el-tag>
          <el-tag v-if="scope.row.isHome === 0" size="small" type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        header-align="center"
        align="center"
        label="排序"
        sortable>
      </el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
        width="200">
        <template slot-scope="scope">
          <el-button type="warning" size="small" @click="addOrUpdateHandle(scope.row)">编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteHandle(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 新增 模态框 -->
    <el-dialog
      :title="!dataForm.id ? '新增' : '编辑'"
      :visible.sync="addTabModel"
      width="1000px"
      center>
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        label-width="110px">
        <el-form-item label="名称">
          <el-input v-model="dataForm.name" placeholder="标题"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="cover-uploader"
            accept=".jpg,.jpeg,.png,.gif"
            :action="actionUpload"
            :show-file-list="false"
            :on-success="(res) => handleAvatarSuccess('imgUrl', res)"
            :before-upload="beforeAvatarUpload">
            <img v-if="dataForm.imgUrl"
              :src="baseImageUrl + dataForm.imgUrl"/>
            <i v-else class="el-icon-plus cover-uploader-icon" />
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="内容:">
          <el-input v-model="dataForm.content" rows="=5" type="textarea"/>
        </el-form-item> -->
        <el-form-item label="内容" prop="content">
            <template>
            <div>
                <el-upload
                class="avatar-uploader edFile"
                :action="actionUpload"
                name="img"
                :data="fileUpload"
                :show-file-list="false"
                :on-success="uploadEdSuccess"
                :on-error="uploadEdError"
                :before-upload="beforeEdUpload">
                </el-upload>
                <quill-editor
                v-model="dataForm.content"
                ref="myQuillEditor"
                :options="editorOption"
                @blur="onEditorBlur($event)"
                @focus="onEditorFocus($event)"
                @change="onEditorChange($event)"
                ></quill-editor>
            </div>
            </template>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="dataForm.type" placeholder="请选择" style="width:100%" clearable="">
            <el-option
              v-for="(item,index) in types" 
              :key="index"
              :label="item"
              :value="index+1">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="是否首页显示" v-if="dataForm.type===2">
          <el-select v-model="dataForm.isHome" placeholder="请选择" style="width:100%" clearable="">
            <el-option :value=1 label="是"/>
            <el-option :value=0 label="否"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number
            v-model="dataForm.sort"
            controls-position="right"
            :min="0"
            label="排序"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addTabModel = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
// import Quill from "quill"; // 富文本基于quill
//默认有工具栏，如果想自定义工具栏可以在toolbarOptions配置，不需要的删掉即可
//想直接使用默认的工具栏删掉editorOption中的modules->toolbar即可
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
  ["blockquote", "code-block"], //引用，代码块

  [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
  [{ list: "ordered" }, { list: "bullet" }], //列表
  [{ script: "sub" }, { script: "super" }], // 上下标
  [{ indent: "-1" }, { indent: "+1" }], // 缩进
  [{ direction: "rtl" }], // 文本方向

  [{ size: ["small", false, "large", "huge"] }], // 字体大小
  [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题

  [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
  [{ font: [] }], //字体
  [{ align: [] }], //对齐方式

  ["clean"], //清除字体样式
  ["image", "video"], //上传图片、上传视频
];

export default {
  components: { quillEditor },
  data() {
    return {
      actionUpload: "http://39.101.136.184:8080",
      dataRule: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
      },
      searchName:null,
      searchType:null,
      dataForm:{id:'',name:'',content:'',imgUrl:'',type:'',isHome:0,sort:0},
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],

      addTabModel: false, //新增 模态框，
      previewImages: [],
      types: [
        "小程序菜单",
        "资讯类型",
        "单车押金须知",
        "单车安全须知",
        "单车游客须知",
        "游船押金须知",
        "游船安全须知",
        "游船游客须知",
        "使用说明"
      ],
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            
            handlers: {
              image: function (value) {
                if (value) {
                  document.querySelector(".edFile input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
        placeholder: "景点详情",
        theme: "snow", //默认即是snow
      },
      fileUpload: {
        //附件上传
        file: null,
      },
    };
  },
  activated() {
    this.getDataList();
  },
  computed: {
    btnMap() {
       return (type) => {
        return this.types[type - 1];
      };
    },
  },
  mounted() {
    this.actionUpload = this.$http.adornUrl(
      `/common/file/upload?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
    getDataList() {
      this.dataListLoading = true;
      this.$http({
        url: this.$http.adornUrl("/setting/list"),
        method: "get",
        params: this.$http.adornParams({
          name:this.searchName,
          type:this.searchType,
          page: this.pageIndex,
          limit: this.pageSize,
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list;
          this.totalPage = data.page.totalCount;
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      });
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val;
      this.getDataList();
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val;
    },
    //详情
    getDataInfo() {
      this.dataListLoading = true;
      this.$http({
          url: this.$http.adornUrl(`/setting/info/${this.dataForm.id}`),
          method: "get",
          params: this.$http.adornParams(),
      }).then(({ data }) => {
        let dataForm = this.dataForm;
        if (data && data.code === 0) {
          let setting = data.setting;
          dataForm.name = setting.name;
          dataForm.content = setting.content;
          dataForm.imgUrl = setting.imgUrl;
          dataForm.isHome = setting.isHome;
          dataForm.sort = setting.sort;
          dataForm.type = setting.type;
        } 
        this.dataListLoading = false;
      });
    },
    // 新增模态框 确定按钮
    dataFormSubmit() {
      let dataForm = this.dataForm;
      const data = {
        id: dataForm.id || null,
        name: dataForm.name,
        content: dataForm.content,
        imgUrl: dataForm.imgUrl,
        type: dataForm.type,
        sort: dataForm.sort,
        url:'',
      };
      //资讯类型--有“是否首页显示”
      if(dataForm.type === 2){
          data["isHome"] = this.dataForm.isHome;
      }else{
          data["isHome"] = '';
      }
      this.$http({
        url: this.$http.adornUrl(
            `/setting/${!dataForm.id ? "save" : "update"}`
        ),
        method: "post",
        data: this.$http.adornData(data),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message.success("操作成功!");
          this.addTabModel = false;
          this.getDataList();
        } else {
          this.$message.error(data.msg);
          this.addTabModel = false;
          this.getDataList();
        }
      });
    },
    // 新增 / 修改
    addOrUpdateHandle(arow) {
      this.addTabModel = true;
      this.dataForm.id = arow ? arow.id : 0;
      if(this.dataForm.id){
        this.getDataInfo();
      }else{
        this.dataForm.name = "";
        this.dataForm.content = "";
        this.dataForm.imgUrl = "";
        this.dataForm.isHome = "";
        this.dataForm.sort = "";
        this.dataForm.type = "";
      }
    },
    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id;
          });
      this.$confirm(
        `确定对[id=${ids.join(",")}]进行[${id ? "删除" : "批量删除"}]操作?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/setting/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.getDataList();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    handleAvatarSuccess(type, res) {
      if (res.code == 200) {
        const list = res.msg[0];
        this.dataForm[type] = list;
      }
    },
    beforeAvatarUpload(file) {
      let isLt10M = file.size / 1024 / 1024 < 10; //设定图片上传 大小限制
      let reg = /\.(jpg|jpeg|png)$/i;
      if (!reg.test(file.name)) {
        this.$message({
          showClose: true,
          message: "上传支持格式（.jpg/.jpeg/.png）",
          type: "error",
        });
        return false;
      } else if (!isLt10M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
        return false;
      }
    },
    deleteImg(index) {
      // this.dataForm.picUrl = "";
    },
    uploadEdError() {
      // loading动画消失
      this.quillUpdateImg = false;
      this.$message.error("图片插入失败");
    },
    uploadEdSuccess(res, file) {
      // 首先获取富文本编辑器的实例
      let quill = this.$refs.myQuillEditor.quill;
      console.log("富文本图片：" + res);
      // 上传成功所执行
      if (res.code == 200 && res.msg[0] !== null) {
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片res为服务器返回的数据
        quill.insertEmbed(length, "image", this.baseImageUrl + res.msg[0]);
        // 光标移动至文本末端
        quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      // loading动画消失
      this.quillUpdateImg = false;
    },
    beforeEdUpload(file) {
      this.fileUpload.file = file;
      // 显示loading动画
      this.quillUpdateImg = true;
    },
    
  },
};
</script>

<style>
.ql-editor{
    min-height: 200px;
}
.cover-uploader .el-upload {
  width: 145px;
  height: 145px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.cover-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 145px;
  height: 145px;
  line-height: 145px;
  text-align: center;
  background-color: #fbfdff;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.deleteImg {
  position: absolute;
  top: 0;
  right: 0;
  display: none;
  font-size: 16px;
  opacity: 0.8;
  padding: 5px !important;
}
.el-upload {
  font-size: 30px;
}

.el-image__inner {
  width: 100px;
  height: 100px;
}
</style>
